#!/usr/bin/python -O

# All imports needed
import sys
import os
import shutil

# utils.py
def sep_extensions(filelist, extension):
    keep_files = []
    for filename in filelist:
        name = filename.split('.')
        if name[len(name) - 1] == extension:
            keep_files.append(filename)

    return keep_files

def show_list(list_of_items):
    counter = 1
    for item in list_of_items:
        print str(counter) + '. ' + item
        counter += 1

    return len(list_of_items)

# save_switcher.py
class SaveSwitcher:
    def __init__(self):
        self.first_run = False
        home = os.getenv("HOME")
        if home == None:
            home = os.getenv('USERPROFILE')
        save_files = ["qsave.vvv", "tsave.vvv", "unlock.vvv"]
        if sys.platform.startswith("linux"):
            self.savedir = home + "/.vvvvvv"
        elif sys.platform.startswith("darwin"):
            self.savedir = home + "/Documents/VVVVVV/Saves"
        elif sys.platform.startswith("win"):
            self.savedir = home + "\\Documents\\VVVVVV\\Saves"
        else:
            raise OSError
        
        self.profiledir = self.savedir + '/../MultiSave'
        
        self.get_save_list()
        
        if not "unlock.vvv" in self.file_list:
            raise IOError

        self.get_backups()
        return

    def get_backups(self):
        if not os.path.isdir(self.profiledir):
            os.mkdir(self.profiledir)
            self.first_run = True
        self.backup_list = os.listdir(self.profiledir)
        return self.backup_list

    def get_save_list(self):
        self.file_list = sep_extensions(os.listdir(self.savedir), 'vvv')
        return self.file_list

    def backup_save(self, name):
        self.get_save_list()
        if os.path.isdir(self.profiledir + '/' + name):
            return False
        os.mkdir(self.profiledir + '/' + name)
        for item in self.file_list:
            input_file = open(self.savedir + '/' + item, 'r')
            output_file = open(self.profiledir + '/' + name + '/'+ item, 'w')

            input_data = input_file.readlines()
            output_file.writelines(input_data)

            input_file.close()
            output_file.close()

        print "Files written to " + self.profiledir + '/' + name
        return True
            

    def restore_save(self, name):
        self.get_save_list()
        
        for item in self.file_list:
            os.remove(self.savedir + '/' + item)
            input_file = open(self.profiledir + '/' + name + '/' + item, 'r')
            output_file = open(self.savedir + '/' + item, 'w')

            input_data = input_file.readlines()
            output_file.writelines(input_data)

            input_file.close()
            output_file.close()

        return True

    def delete_save(self, name):
        self.get_save_list()
        shutil.rmtree(self.profiledir + '/' + name)

# main.py
def main():
    try:
        save_switcher = SaveSwitcher()

    except OSError:
        print "Invalid OS"

    except IOError:
        print "No save file found. Please start VVVVVV ",
        print "and run this program again."

    else:
        menu_items = ['show', 'backup', 'restore', 'exit']

        if save_switcher.first_run:
            print "First run detected... "
            print save_switcher.profiledir + " created"
            print

        else:
            print "Backup directory is " + save_switcher.profiledir
            print

        not_done = True

        print "Welcome to VVVVVV MultiSave"

        while not_done:
            print
            print "Main Menu:"
            print "1. Show backups"
            print "2. Create Backup of Save"
            print "3. Restore from Backup of Save"
            print "4. Delete Backup"
            print "q. Quit"
            choice = raw_input("Choice: ")
            print
            
            if choice == "1":
                if save_switcher.get_backups():
                    print "Here's a list of your backups"
                    show_list(save_switcher.get_backups())

                else:
                    print "There are currently no backups"
                        

            elif choice == "2":
                not_finished = True
                while not_finished:
                    if save_switcher.get_backups():
                        print "Here's a list of your backups"
                        num_backups = show_list(save_switcher.get_backups())
                        print "You have " + str(num_backups) + " backup(s)"

                    else:
                        print "There are currently no backups"
                        
                    print "Please enter a name for the backup"
                    print "or 'quit' (without the quotes) to return to the ",
                    print "main menu"
                    backup_name = raw_input("Name: ")
                    if backup_name == 'quit':
                        not_finished = False
                        break
                    elif ';' in backup_name:
                        print "Sorry, we don't take semicolons. It throws a ",
                        print "spanner in our cogs"
                        print
                        continue
                    try:
                        success = save_switcher.backup_save(backup_name)

                    except IOError:
                        print "You do not have access to the directory."
                        continue

                    else:
                        if not success:
                            print "An Error Occurred. Perhaps use a ",
                            print "different backup name?"
                            continue
                        not_finished = False
                        break

            elif choice == "3" and save_switcher.get_backups():
                print "WARNING: WILL OVERWRITE CURRENT SAVE"
                print "If you have not done so already, it is strongly advised to"
                print "enter 'quit' at the next prompt and make a backup NOW"
                print
                print "Here's a list of your backups"
                num_backups = show_list(save_switcher.get_backups())
                print "You have " + str(num_backups) + " backup(s)"
                print "Enter the name of the backup that you wish to restore"
                print "or 'quit' (without quotes) to return to the main menu"

                backup_name = raw_input("Name: ")
                if backup_name == 'quit':
                    continue

                save_switcher.restore_save(backup_name)
                print "Done!"

            elif choice == "4" and save_switcher.get_backups():
                print "Here's a list of your backups"
                num_backups = show_list(save_switcher.get_backups())
                
                print "You have " + str(num_backups) + " backup(s)"
                print "Enter the name of the backup that you wish to delete"
                print "or 'quit' (without quotes) to return to the main menu"
                print "WARNING: THIS CANNOT BE UNDONE"

                backup_name = raw_input("Name: ")

                if backup_name == 'quit':
                    continue

                save_switcher.delete_save(backup_name)
                print "Done!"
                
            elif choice == "q" or choice == "Q":
                not_done = False
                print "Quitting..."

            else:
                print "Invalid Choice"
                
if __name__ == "__main__":
    main()
